package com.yuba.web.service.impl.front;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yuba.common.core.constant.Constants;
import com.yuba.common.core.constant.GlobalConstants;
import com.yuba.common.core.domain.model.LoginUser;
import com.yuba.common.core.domain.model.PasswordLoginBody;
import com.yuba.common.core.enums.LoginType;
import com.yuba.common.core.enums.UserStatus;
import com.yuba.common.core.exception.user.CaptchaException;
import com.yuba.common.core.exception.user.CaptchaExpireException;
import com.yuba.common.core.exception.user.UserException;
import com.yuba.common.core.utils.MessageUtils;
import com.yuba.common.core.utils.StringUtils;
import com.yuba.common.core.utils.ValidatorUtils;
import com.yuba.common.json.utils.JsonUtils;
import com.yuba.common.redis.utils.RedisUtils;
import com.yuba.common.satoken.utils.LoginHelper;
import com.yuba.common.web.config.properties.CaptchaProperties;
import com.yuba.front.domain.vo.FrontUserVo;
import com.yuba.front.service.IFrontUserService;
import com.yuba.system.domain.vo.SysClientVo;
import com.yuba.web.domain.vo.LoginVo;
import com.yuba.web.service.IAuthStrategy;
import com.yuba.web.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@RequiredArgsConstructor
@Service("front_password" + IAuthStrategy.BASE_NAME)
public class FrontPasswordAuthStrategy implements IAuthStrategy {

    private final CaptchaProperties captchaProperties;
    private final SysLoginService loginService;
    private final IFrontUserService userService;

    @Override
    public LoginVo login(String body, SysClientVo client) {
        // 1 解析body
        PasswordLoginBody loginBody = JsonUtils.parseObject(body, PasswordLoginBody.class);
        ValidatorUtils.validate(loginBody);
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String code = loginBody.getCode();
        String uuid = loginBody.getUuid();

        // 2 校验验证码
        Boolean captchaEnable = captchaProperties.getEnable();
        if (captchaEnable) {
            validateCaptcha(null, username, code, uuid);
        }

        // 3 查询用户
        FrontUserVo user = loadUserByUsername(username);
        // 4 校验密码
        loginService.checkLogin(LoginType.PASSWORD, null, user.getUsername(), ()-> !BCrypt.checkpw(password, user.getPassword()));
        LoginUser loginUser = buildLoginUser(user, client);

        // 5 构建SaLoginModel
        SaLoginModel model = new SaLoginModel();
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());

        // 6 使用LoginHelper来进行登录
        LoginHelper.login(loginUser, model);

        // 7 返回LoginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());
        return loginVo;
    }

    private FrontUserVo loadUserByUsername(String username) {
        FrontUserVo user = userService.loadUserByUsername(username);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UserException("user.not.exists", username);
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UserException("user.blocked", username);
        }
        return user;
    }

    private LoginUser buildLoginUser(FrontUserVo user, SysClientVo client) {
        // 构建自己的loginUser
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUsername(user.getUsername());
        loginUser.setNickname(user.getNickname());
        loginUser.setUserType(user.getUserType());
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        return loginUser;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    private void validateCaptcha(String tenantId, String username, String code, String uuid) {
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            loginService.recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            loginService.recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
    }
}
